package com.yq.netty.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ClassName NIOFileChannel03
 * @Description 用一个buffer完成文件的读写，使用fileChannel 的 read write
 * @Author yaoqiang
 * @Date 2021/3/24 9:58
 * @Version 1.0
 */
public class NIOFileChannel03 {
    public static void main(String[] args) throws IOException {
        //创建文件输入流
        FileInputStream fileInputStream = new FileInputStream("src/main/java/com/yq/netty/nio/1.txt");
        FileChannel channel1 = fileInputStream.getChannel();
        FileOutputStream fileOutputStream = new FileOutputStream("src/main/java/com/yq/netty/nio/2.txt");
        FileChannel channel2 = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true){//循环读取
            byteBuffer.clear();//将标志位重置,清空buffer
            int read = channel1.read(byteBuffer);
            if (read!=-1){
                byteBuffer.flip();
                channel2.write(byteBuffer);
            }else {
                break;
            }
        }
        fileInputStream.close(); fileOutputStream.close();
    }
}
